<script setup lang="ts">
import { buyerOrderPage } from "~/api/user";
import { useOrderStore } from "~/store/useOrder";
import { useImageCache } from "~/composables/useImageCache";

// 使用图片缓存功能
const { getCoverImage, preloadImages } = useImageCache();

useSeoMeta({
  title: "我的订单 - 技能猴子",
  ogTitle: "我的订单 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const orderStore = useOrderStore();
const router = useRouter();
const toOrderDetails = (item: any) => {
  router.push(`/orderDetails?orderSn=${item.orderSn}`);
};

onMounted(() => {
  getList();
});
const params = ref({
  pageNum: 1,
  pageSize: 10,
});
const list = ref([]);
const total = ref(0);
const listLoading = ref(false);
const getList = async () => {
  listLoading.value = true;
  try {
    const data = await buyerOrderPage(params.value);
    list.value = data.data.records;
    total.value = data.data.total;
    
    // 预加载订单列表中的图片
    const imagesToPreload = [];
    list.value.forEach(item => {
      if (item.coverPic) imagesToPreload.push(item.coverPic);
      if (item.shopAvatar) imagesToPreload.push(item.shopAvatar);
    });
    preloadImages(imagesToPreload);
  } catch (e) {
    console.log(e);
  } finally {
    listLoading.value = false;
  }
};
// 分页
const currentChange = (pageNum: number) => {
  params.value.pageNum = pageNum;
  getList();
};
// 切换订单状态查询
// 状态映射：tab显示顺序 -> 实际状态值
// tab索引: 0:待支付 1:待开启 2:已取消 3:履约中 4:已交付 5:待评价 6:已完成
// 实际状态值: 0:待支付 1:待开启 6:已取消 2:履约中 3:已交付 4:待评价 5:已完成
const statusMap: Record<number, number> = {
  0: 0,  // 待支付 -> 状态值 0
  1: 1,  // 待开启 -> 状态值 1
  2: 6,  // 已取消 -> 状态值 6
  3: 2,  // 履约中 -> 状态值 2
  4: 3,  // 已交付 -> 状态值 3
  5: 4,  // 待评价 -> 状态值 4
  6: 5,  // 已完成 -> 状态值 5
};

// 判断tab是否激活
const isTabActive = (tabIndex: number | null) => {
  if (tabIndex === null) {
    return params.value.status === undefined;
  }
  const actualStatus = statusMap[tabIndex];
  return params.value.status === actualStatus;
};

const tabActiveHandle = (tabIndex: number | null) => {
  if (tabIndex === null) {
    delete params.value.status;
  } else {
    // 将tab索引映射到实际状态值发送给接口
    params.value.status = statusMap[tabIndex];
  }
  params.value.pageNum = 1;
  getList();
};
// 评价
const evaluateShow = ref(false);
const evaluateItem = ref({});
const toEvaluate = (item) => {
  evaluateItem.value = item;
  evaluateShow.value = true;
};

// 去支付
const toPay = (item) => {
  if (payRemainTime(item) === "已过期") {
    return ElMessage.error("订单已过期");
  }
  orderStore.setPayInfo(item);
  router.push(`/pay?orderSn=${item.orderSn}`);
};
// 支付剩余时间,返回剩余时间,格式 时:分
const payRemainTime = (item) => {
  // 如果没有remainingTime字段，根据创建时间计算（假设30分钟支付时限）
  if (!item.remainingTime) {
    const createTime = new Date(item.createTime).getTime();
    const endTime = createTime + 30 * 60 * 1000; // 30分钟后过期
    const nowTime = new Date().getTime();
    const remainTime = endTime - nowTime;
    if (remainTime <= 0 && item.status === '0') return "已过期";
    const hours = Math.floor(remainTime / (60 * 60 * 1000));
    const minutes = Math.floor((remainTime % (60 * 60 * 1000)) / (60 * 1000));
    return `${hours < 10 ? "0" + hours : hours}小时${
      minutes < 10 ? "0" + minutes : minutes
    }分钟`;
  }
  
  const endTime = new Date(item.remainingTime).getTime();
  const nowTime = new Date().getTime();
  const remainTime = endTime - nowTime;
  if (remainTime <= 0 && item.status === '0') return "已过期";
  const hours = Math.floor(remainTime / (60 * 60 * 1000));
  const minutes = Math.floor((remainTime % (60 * 60 * 1000)) / (60 * 1000));
  return `${hours < 10 ? "0" + hours : hours}小时${
    minutes < 10 ? "0" + minutes : minutes
  }分钟`;
};
const evaluateClose = (status) => {
  if (status === "send") {
    getList();
  }
  evaluateShow.value = false;
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="body">
    <h4 class="page-title">我的订单</h4>
    <div class="order-box">
      <p class="tab">
        <span
          :class="{ active: isTabActive(null) }"
          @click="tabActiveHandle(null)"
          >全部</span
        >
        <span :class="{ active: isTabActive(0) }" @click="tabActiveHandle(0)"
          >待支付</span
        >
        <span :class="{ active: isTabActive(1) }" @click="tabActiveHandle(1)"
          >待开启</span
        >
        <span :class="{ active: isTabActive(2) }" @click="tabActiveHandle(2)"
          >已取消</span
        >
        <span :class="{ active: isTabActive(3) }" @click="tabActiveHandle(3)"
          >履约中</span
        >
        <span :class="{ active: isTabActive(4) }" @click="tabActiveHandle(4)"
          >已交付</span
        >
        <span :class="{ active: isTabActive(5) }" @click="tabActiveHandle(5)"
          >待评价</span
        >
        <span :class="{ active: isTabActive(6) }" @click="tabActiveHandle(6)"
          >已完成</span
        >
      </p>
      <div class="order-table" v-loading="listLoading">
        <div class="table-header">
          <span>服务</span><span>类型</span><span>卖家</span><span>开始时间</span
          ><span>结束时间</span><span>总价</span><span>状态</span>
        </div>
        <div class="table-body">
          <el-empty v-if="!list || list.length===0"></el-empty>
          <div class="tr" v-for="item of list" :key="item.id">
            <div class="td goods" @click="toOrderDetails(item)">
              <img v-if="item.coverPic" :src="getCoverImage(item.coverPic)" alt="" />
              <img v-else src="~/assets/app-mj.png" alt="" />
              <h4 :title="item.goodsName">{{ item.goodsName }}</h4>
            </div>
            <span class="td">{{ item.goodsTypeName || "-" }}</span>
            <span class="td">
              <div class="user">
                <img v-if="item.shopAvatar" :src="getCoverImage(item.shopAvatar)" alt="" />
                <img v-else src="~/assets/app-mj.png" alt="" />
                <span>{{ item.shopName }}</span>
              </div>
            </span>
            <span class="td">{{ item.startTime? item.startTime.substring(0,16) : "-" }}</span>
            <span class="td">{{ item.endTime? item.endTime.substring(0,16) : "-" }}</span>
            <span class="td">¥{{ item.payAmount }}</span>
            <div class="td">
              <div
                :class="[
                  `status-${item.status}`,
                  `${payRemainTime(item) === '已过期' ? 'status-2' : ''}`,
                ]"
              >
                <p>
                  <span></span
                  >{{  
                    payRemainTime(item) === "已过期"
                      ? "已取消"
                      : item.status==='5'?'待评价':orderStore.getOrderStatusName(item.status)
                  }}
                </p>
                <p
                  v-if="item.status === '0'"
                  style="color: #157c4c; cursor: pointer"
                  @click="toPay(item)"
                >
                  <span
                    v-if="payRemainTime(item) !== '已过期'"
                    :class="{ 'text-red': payRemainTime(item) === '已过期' }"
                    >{{ payRemainTime(item) }}</span
                  >
                </p>
                <p v-if="item.status === '4'">去确认</p>
                <!-- <p
                  v-if="item.status === 5"
                  style="color: #157c4c; padding-left: 13px; cursor: pointer"
                  @click="toEvaluate(item)"
                >
                  去评价
                </p> -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="params.pageSize"
          :current-page="params.pageNum"
          @current-change="currentChange"
        />
      </div>
    </div>
  </div>
  <BaseFooter />
  <DialogEvaluate
    v-if="evaluateShow"
    :orderDetails="evaluateItem"
    @close="evaluateClose"
  />
</template>

<style scoped lang="scss">
.body {
  background: #f9f9f9;
  padding-top: 80px;
  padding-bottom: 36px;
}
.page-title {
  width: 1100px;
  margin: 0 auto;
  padding-top: 32px;
  padding-bottom: 16px;
  font-size: 20px;
  color: #191e28;
}
.order-box {
  width: 1100px;
  margin: 0 auto;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  padding: 24px 20px;
  box-sizing: border-box;
  background: #fff;
}
.tab {
  display: flex;
  border-bottom: 1px solid rgba(237, 237, 238, 1);
  span {
    margin-right: 40px;
    color: #191e28;
    font-size: 16px;
    line-height: 30px;
    padding: 13px 0;
    cursor: pointer;
    &:hover {
      color: #1dbf73;
    }
    &.active {
      position: relative;
      color: #1dbf73;
      font-weight: bold;
      &:after {
        content: "";
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background: #1dbf73;
        border-radius: 2px;
        transition: all 0.3s;
      }
    }
  }
}
.order-table {
  border: 1px solid #e5e7eb;
  margin-top: 24px;
  margin-bottom: 24px;
  border-radius: 8px;
  min-height: 300px;
  .table-header {
    padding: 0 24px;
    box-sizing: border-box;
    display: flex;
    border-bottom: 1px solid #e5e7eb;
    span {
      line-height: 54px;
      display: inline-block;
      color: #191e28;
      font-weight: bold;
    }
    span:nth-child(1) {
      flex: 0 0 220px;
    }
    span:nth-child(2) {
      flex: 0 0 78px;
    }
    span:nth-child(3) {
      flex: 0 0 160px;
    }
    span:nth-child(4) {
      flex: 0 0 175px;
    }
    span:nth-child(5) {
      flex: 0 0 175px;
    }
    span:nth-child(6) {
      flex: 0 0 75px;
    }
    span:nth-child(7) {
      flex: 1;
    }
  }
  .table-body {
    .tr {
      display: flex;
      align-items: center;
      padding: 16px 24px;
      box-sizing: border-box;
      border-bottom: 1px solid #e5e7eb;
      &:last-child {
        border: none;
      }
      .td {
        color: #191e28;
      }
      .td:nth-child(1) {
        flex: 0 0 220px;
      }
      .td:nth-child(2) {
        flex: 0 0 78px;
      }
      .td:nth-child(3) {
        flex: 0 0 160px;
      }
      .td:nth-child(4) {
        flex: 0 0 175px;
      }
      .td:nth-child(5) {
        flex: 0 0 175px;
      }
      .td:nth-child(6) {
        flex: 0 0 75px;
      }
      .td:nth-child(7) {
        flex: 1;
      }
    }
    .goods {
      display: flex;
      align-items: center;
      cursor: pointer;
      img {
        max-width: 60px;
        max-height: 40px;
        margin-right: 8px;
        border-radius: 8px;
        object-fit: cover;
      }
      h4 {
        font-size: 13px;
        font-weight: 600;
        padding-right: 20px;
        box-sizing: border-box;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        width: 160px;
        height: 35px;
        overflow: hidden;
      }
    }
    .user {
      display: flex;
      align-items: center;
      img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 8px;
        object-fit: cover;
      }
      span {
        color: #191e28;
      }
    }
    .status-0 {
      display: flex;
      flex-direction: column;
      color: rgba(25, 30, 40, 0.6);
      font-weight: bold;
      p:nth-child(1) {
        display: flex;
        align-items: center;
        span {
          display: inline-block;
          width: 4px;
          height: 4px;
          flex: 0 0 4px;
          background: rgba(25, 30, 40, 0.6);
          border-radius: 50%;
          border: 2px solid rgba(25, 30, 40, 0.6);
          margin-right: 6px;
        }
      }
      p:nth-child(2) {
        font-size: 12px;
        color: #157c4c;
      }
    }
    .status-1 {
      display: flex;
      flex-direction: column;
      color: rgba(25, 30, 40, 0.6);
      font-weight: bold;
      p:nth-child(1) {
        display: flex;
        align-items: center;
        color: #3B82F6;
        span {
          display: inline-block;
          width: 4px;
          height: 4px;
          flex: 0 0 4px;
          background: #3B82F6;
          border-radius: 50%;
          border: 2px solid rgba(59, 130, 246, 0.32);
          margin-right: 6px;
        }
      }
      p:nth-child(2) {
        font-size: 12px;
        color: #ff4f4f;
      }
    }
    .status-2 {
      display: flex;
      align-items: center;
      color: rgba(25, 30, 40, 0.6);
      font-weight: bold;
      span {
        display: inline-block;
        width: 4px;
        flex: 0 0 4px;
        height: 4px;
        background: rgba(25, 30, 40, 0.6);
        border-radius: 50%;
        border: 2px solid rgba(25, 30, 40, 0.6);
        margin-right: 6px;
      }
    }
    .status-3 {
      display: flex;
      align-items: center;
      color: #1DBF73;
      font-weight: bold;
      span {
        display: inline-block;
        width: 4px;
        height: 4px;
        flex: 0 0 4px;
        background: #1DBF73;
        border-radius: 50%;
        border: 2px solid rgba(29, 191, 115, 0.32);
        margin-right: 6px;
      }
    }
    .status-4 {
      display: flex;
      align-items: center;
      color: #1dbf73;
      font-weight: bold;
      span {
        display: inline-block;
        width: 4px;
        height: 4px;
        flex: 0 0 4px;
        background: #1dbf73;
        border-radius: 50%;
        border: 2px solid #1dbf73;
        margin-right: 6px;
      }
    }
    .status-5 {
      display: flex;
      align-items: center;
      color: #019a81;
      font-weight: bold;
      span {
        display: inline-block;
        width: 4px;
        height: 4px;
        flex: 0 0 4px;
        background: #019a81;
        border-radius: 50%;
        border: 2px solid rgba(1, 154, 129, 0.32);
        margin-right: 6px;
      }
    }
    .status-6 {
      display: flex;
      align-items: center;
      color: rgba(25, 30, 40, 0.6);
      font-weight: bold;
      span {
        display: inline-block;
        width: 4px;
        height: 4px;
        flex: 0 0 4px;
        background: rgba(25, 30, 40, 0.6);
        border-radius: 50%;
        border: 2px solid rgba(25, 30, 40, 0.6);
        margin-right: 6px;
      }
    }
    span.text-red {
      color: red;
    }
  }
}
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

<style lang="scss">
.order-box .el-pagination button:disabled {
  background: none;
}
.order-box .el-pagination button.is-first {
  margin-right: 6px;
}
.order-box .el-pagination button.is-last {
  background: none;
  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}
.order-box .el-pager li {
  background: none;
  width: 36px;
  height: 36px;
  margin-right: 6px;
  &:hover {
    font-weight: bold;
    color: #191e28;
  }
}
.order-box .el-pager li.is-active {
  background: #fff;
  box-shadow: 0 0 16px 0 rgba(11, 13, 18, 0.06);
  border-radius: 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  color: #191e28;
}
.order-box .el-checkbox.el-checkbox--large .el-checkbox__inner {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  display: flex;
}
.order-box .el-checkbox__input.is-checked .el-checkbox__inner {
  background: #1dbf73;
  border: 1px solid #1dbf73;
}
.order-box .el-checkbox__inner:after {
  top: 3px;
  left: 7px;
}
</style>
